# -*- coding: utf-8 -*- 
import sys, os
path = os.path.join(request.folder, 'modules')
if not path in sys.path:
    sys.path.append(path)
import logging
from gluon.tools import fetch
from xml.dom import minidom
import urllib
import cgi
from douban.service import DoubanService
from douban.client import OAuthClient
import doubanHelper
import logging

API_KEY='01fd3f6ce981d9c505f7be46bc858d4f'
SECRET='0d55bcd37ef0cd1f'
HOST = 'http://www.douban.com'

def index():
    session.forget()
    member_number = len(db().select(db.members.ALL))
    return dict(member_number=member_number)

	
def doubanAuth():
    session.request_tokens = {}
    session.access_tokens = {} 
    client = OAuthClient(key=API_KEY, secret=SECRET)
    key, secret = client.get_request_token()
    if key and secret:
        session.request_tokens[key] = secret
        url = client.get_authorization_url(key, secret, 
                                           callback=request.env.wsgi_url_scheme + '://' + request.env.http_host + URL(r=request, f='granted'))
        redirect(url)
    else:
        return '获取 Request Token 失败'

    
def granted():
    client = OAuthClient(key=API_KEY, secret=SECRET)
    request_key = request.vars.oauth_token
    request_secret = session.request_tokens.get(request_key)
    try:           
        access_key, access_secret, user_id = \
            client.get_access_token(request_key, request_secret)
        if access_key and access_secret:
            # store user access key in cookie, 
            # not accessible by other people
            session.access_key = access_key
            session.access_tokens[access_key] = access_secret
    except Exception:
        access_token = None
        return '获取用户授权失败'
    redirect(URL(r=request, f='checkin'))

def checkin():
    access_key = session.access_key
    access_secret = session.access_tokens[access_key]
    doubanservice = DoubanService(api_key=API_KEY, secret=SECRET)
    doubanservice.ProgrammaticLogin(access_key, access_secret)
    myprofile = doubanservice.GetAuthorizedUID('/people/@me')
    result = minidom.parseString(str(myprofile))
    try:
        sig = result.getElementsByTagName('ns1:signature')[0].firstChild.toxml()
    except:
        sig = 'None'
    try:
        for node in result.getElementsByTagName('ns0:link'):
            if node.attributes['rel'].value == 'icon':
                pic_url=node.attributes['href'].value
    except:
        pic_url = ''
    try:
        location = myprofile.location.text
    except:
        location = 'Unknown'
    try:
        content = myprofile.content.text
    except:
        content = ''
    result_div = DIV(DIV(IMG(_src=pic_url, _alt='Photo'), _id='pic'),
                     DIV(H3('用户名: ', B(myprofile.title.text), ' (', sig, ')'),
                         H3('活动地区: ', B(location)),  _id='intro'),
                     DIV(P(PRE(content)), _id='chang'),
                     _id='info', _class='box')
    return dict(result_div=result_div)

@auth.requires_login()
def fetchGroupInfo():
    robotchicken = doubanHelper.groupAgent()
    return robotchicken.getGroupPage()

def user():
    """
    exposes:
    http://..../[app]/default/user/login 
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    session.forget()
    return service()
